<!DOCTYPE html>
<html>
<head>
    

    

    
<!-- Baidu Tongji -->
<script>var _hmt = _hmt || []</script>
<script async src="//hm.baidu.com/hm.js?a7c05ce530152d9866930ef4850ee566"></script>
<!-- End Baidu Tongji -->




    <meta charset="utf-8">
    
    
    
    <title>Metrics-JVM上的实时监控类库 | 神奇的鸭鸭の码农库 | 新知识要不断的总结记录成笔记，要多写，多画，能够清晰透彻的将知识讲给别人听，才是达到理解的层次。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#765959">
    
    
    <meta name="keywords" content="监控平台">
    <meta name="description" content="当我们需要为某个系统某个服务做监控、做统计，就需要用到Metrics。举个例子，一个图片压缩服务：  每秒钟的请求数是多少(TPS)? 平均每个请求处理的时间？ 请求处理的最长耗时？ 等待处理的请求队列的长度？  基本上每一个服务，应用都需要做一个监控系统，这需要尽量以少量的代码，实现统计某类数据的功能。 导入基本使用方式直接将core包导入pom文件即可，配置如下：123456&amp;lt;!-- 阿">
<meta name="keywords" content="监控平台">
<meta property="og:type" content="article">
<meta property="og:title" content="Metrics-JVM上的实时监控类库">
<meta property="og:url" content="http://magic_duck.oschina.io/2017/11/13/Metrics/index.html">
<meta property="og:site_name" content="神奇的鸭鸭の码农库">
<meta property="og:description" content="当我们需要为某个系统某个服务做监控、做统计，就需要用到Metrics。举个例子，一个图片压缩服务：  每秒钟的请求数是多少(TPS)? 平均每个请求处理的时间？ 请求处理的最长耗时？ 等待处理的请求队列的长度？  基本上每一个服务，应用都需要做一个监控系统，这需要尽量以少量的代码，实现统计某类数据的功能。 导入基本使用方式直接将core包导入pom文件即可，配置如下：123456&amp;lt;!-- 阿">
<meta property="og:updated_time" content="2017-12-05T09:58:35.279Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Metrics-JVM上的实时监控类库">
<meta name="twitter:description" content="当我们需要为某个系统某个服务做监控、做统计，就需要用到Metrics。举个例子，一个图片压缩服务：  每秒钟的请求数是多少(TPS)? 平均每个请求处理的时间？ 请求处理的最长耗时？ 等待处理的请求队列的长度？  基本上每一个服务，应用都需要做一个监控系统，这需要尽量以少量的代码，实现统计某类数据的功能。 导入基本使用方式直接将core包导入pom文件即可，配置如下：123456&amp;lt;!-- 阿">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.4.3">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">神奇的鸭鸭</h5>
          <a href="mailto:702038338@qq.com" title="702038338@qq.com" class="mail">702038338@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/magic_duck" target="_blank" >
                <i class="icon icon-lg icon-gg-circle"></i>
                码云
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.zhihu.com/people/shen-qi-de-ya-ya" target="_blank" >
                <i class="icon icon-lg icon-twitter"></i>
                知乎
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/404.html"  >
                <i class="icon icon-lg icon-link"></i>
                404页面测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">Metrics-JVM上的实时监控类库</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">Metrics-JVM上的实时监控类库</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-11-12T16:00:00.000Z" itemprop="datePublished" class="page-time">
  2017-11-13
</time>


            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#导入"><span class="post-toc-number">1.</span> <span class="post-toc-text">导入</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#五种Metrics类型"><span class="post-toc-number">2.</span> <span class="post-toc-text">五种Metrics类型</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Gauges"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">Gauges</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Counters"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">Counters</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Meters"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">Meters</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Histograms"><span class="post-toc-number">2.4.</span> <span class="post-toc-text">Histograms</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Timers"><span class="post-toc-number">2.5.</span> <span class="post-toc-text">Timers</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Health-Checks"><span class="post-toc-number">3.</span> <span class="post-toc-text">Health Checks</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#其他支持"><span class="post-toc-number">4.</span> <span class="post-toc-text">其他支持</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#参考资料"><span class="post-toc-number">5.</span> <span class="post-toc-text">参考资料</span></a></li></ol>
        </nav>
    </aside>
    
<article id="post-Metrics"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">Metrics-JVM上的实时监控类库</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年11月13日 0:00" datetime="2017-11-12T16:00:00.000Z"  itemprop="datePublished">2017-11-13</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>当我们需要为某个系统某个服务做监控、做统计，就需要用到Metrics。举个例子，一个图片压缩服务：</p>
<ol>
<li>每秒钟的请求数是多少(TPS)?</li>
<li>平均每个请求处理的时间？</li>
<li>请求处理的最长耗时？</li>
<li>等待处理的请求队列的长度？</li>
</ol>
<p>基本上每一个服务，应用都需要做一个监控系统，这需要尽量以少量的代码，实现统计某类数据的功能。</p>
<h2 id="导入"><a href="#导入" class="headerlink" title="导入"></a>导入</h2><p>基本使用方式直接将core包导入pom文件即可，配置如下：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 阿里maven --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.yammer.metrics<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>metrics-core<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.0.0-BETA1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p><strong>core包主要提供如下核心功能：</strong></p>
<ul>
<li>Metrics Registries类似一个metrics容器，维护一个Map，可以是一个服务一个实例。</li>
<li>支持五种Metric类型：Gauges，Counters，Meters，Histograms和Timers。</li>
<li>可以将metrics值通过JMX，Console，CSV文件和SLF4J loggers发布出来。</li>
</ul>
<h2 id="五种Metrics类型"><a href="#五种Metrics类型" class="headerlink" title="五种Metrics类型"></a>五种Metrics类型</h2><h3 id="Gauges"><a href="#Gauges" class="headerlink" title="Gauges"></a>Gauges</h3><p>Gauges是一个最简单的计量，一般用来统计瞬时状态的数据信息，比如系统中处于pending状态的job。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestGauges</span> </span>&#123;</div><div class="line">    <span class="comment">// 实例化一个registry，最核心的一个模块，相当于一个应用程序的metrics系统的容器，维护一个Map</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> MetricRegistry metrics = <span class="keyword">new</span> MetricRegistry(<span class="string">"metrics1"</span>);</div><div class="line">    <span class="comment">// 在控制台上打印输出</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).build();</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Queue&lt;String&gt; queue = <span class="keyword">new</span> LinkedBlockingDeque&lt;String&gt;();</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</div><div class="line">        reporter.start(<span class="number">3</span>, TimeUnit.SECONDS);</div><div class="line">        <span class="comment">// 实例化一个Gauge</span></div><div class="line">        Gauge&lt;Integer&gt; gauge = <span class="keyword">new</span> Gauge&lt;Integer&gt;() &#123;</div><div class="line">            <span class="function"><span class="keyword">public</span> Integer <span class="title">getValue</span><span class="params">()</span> </span>&#123;</div><div class="line">                <span class="keyword">return</span> queue.size();</div><div class="line">            &#125;</div><div class="line">        &#125;;</div><div class="line">        <span class="comment">// 注册到容器中</span></div><div class="line">        metrics.register(MetricRegistry.name(TestGauges2.class, <span class="string">"pending-job"</span>, <span class="string">"size"</span>), gauge);</div><div class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">20</span>; i++) &#123;</div><div class="line">            queue.add(<span class="string">"a"</span>);</div><div class="line">            <span class="comment">// pending</span></div><div class="line">            Thread.sleep(<span class="number">1000</span>);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">console output:</span></div><div class="line"><span class="comment">17-11-13 21:42:35 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Gauges ----------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestGauges2.pending-job.size</span></div><div class="line"><span class="comment">             value = 3</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">17-11-13 21:42:38 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Gauges ----------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestGauges2.pending-job.size</span></div><div class="line"><span class="comment">             value = 6</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">17-11-13 21:42:41 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Gauges ----------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestGauges2.pending-job.size</span></div><div class="line"><span class="comment">             value = 9</span></div><div class="line"><span class="comment">*/</span></div></pre></td></tr></table></figure></p>
<p>通过以上步骤将会向MetricsRegistry容器中注册一个名字为Metrics.TestGauges2.pending-job.size的metrics，实时获取队列长度的指标。另外，Core包还扩展了几种特定的Gauge：</p>
<ul>
<li>JMX Gauges—提供给第三方库只通过JMX将指标暴露出来。</li>
<li>Ratio Gauges—简单地通过创建一个gauge计算两个数的比值。</li>
<li>Cached Gauges—对某些计量指标提供缓存</li>
<li>Derivative Gauges—提供Gauge的值是基于其他Gauge值的接口。</li>
</ul>
<h3 id="Counters"><a href="#Counters" class="headerlink" title="Counters"></a>Counters</h3><p>Counter是Gauge的一个特例，维护一个计数器，可以通过inc()和dec()方法对计数器做修改。使用步骤与Gauge基本类似，在MetricRegistry中提供了静态方法可以直接实例化一个Counter。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestCounter</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> MetricRegistry metrics = <span class="keyword">new</span> MetricRegistry(<span class="string">"name"</span>);</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).build();</div><div class="line">    <span class="comment">// 实例化一个Counter</span></div><div class="line">    <span class="comment">// metrics.register(MetricRegistry.name(TestCounter.class, "pending-jobs"), new Counter());</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Counter pendingJobs = metrics.counter(MetricRegistry.name(TestCounter.class, <span class="string">"pedding-jobs"</span>));</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Queue&lt;String&gt; queue = <span class="keyword">new</span> LinkedList&lt;String&gt;();</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(String str)</span> </span>&#123;</div><div class="line">        pendingJobs.inc();</div><div class="line">        queue.add(str);</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">take</span><span class="params">()</span> </span>&#123;</div><div class="line">        pendingJobs.dec();</div><div class="line">        <span class="keyword">return</span> queue.poll();</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</div><div class="line">        reporter.start(<span class="number">3</span>, TimeUnit.SECONDS);</div><div class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</div><div class="line">            add(<span class="string">"1"</span>);</div><div class="line">            Thread.sleep(<span class="number">1000</span>);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">17-11-13 21:53:05 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Counters --------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestCounter.pedding-jobs</span></div><div class="line"><span class="comment">             count = 4</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">17-11-13 21:53:08 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Counters --------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestCounter.pedding-jobs</span></div><div class="line"><span class="comment">             count = 6</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">17-11-13 21:53:11 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Counters --------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestCounter.pedding-jobs</span></div><div class="line"><span class="comment">             count = 9</span></div><div class="line"><span class="comment">*/</span></div></pre></td></tr></table></figure></p>
<h3 id="Meters"><a href="#Meters" class="headerlink" title="Meters"></a>Meters</h3><p>Meters用来度量某个时间段的平均处理次数（request per second），每1、5、15分钟的TPS。比如一个service的请求数，通过metrics.meter()实例化一个Meter之后，然后通过meter.mark()方法就能将本次请求记录下来。统计结果有总的请求数，平均每秒的请求数，以及最近的1、5、15分钟的平均TPS。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestMeters</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> MetricRegistry metrics = <span class="keyword">new</span> MetricRegistry(<span class="string">"name"</span>);</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).build();</div><div class="line">    <span class="comment">// 实例化一个Meter</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Meter requests = metrics.meter(MetricRegistry.name(TestMeters.class, <span class="string">"request"</span>));</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handleReuqest</span><span class="params">()</span> </span>&#123;</div><div class="line">        requests.mark();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</div><div class="line">        reporter.start(<span class="number">3</span>, TimeUnit.SECONDS);</div><div class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</div><div class="line">            handleReuqest();</div><div class="line">            Thread.sleep(<span class="number">10</span>);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">17-11-13 21:58:15 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Meters ----------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestMeters.request</span></div><div class="line"><span class="comment">             count = 292</span></div><div class="line"><span class="comment">         mean rate = 96.48 events/second</span></div><div class="line"><span class="comment">     1-minute rate = 0.00 events/second</span></div><div class="line"><span class="comment">     5-minute rate = 0.00 events/second</span></div><div class="line"><span class="comment">    15-minute rate = 0.00 events/second</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">17-11-13 21:58:18 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Meters ----------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestMeters.request</span></div><div class="line"><span class="comment">             count = 579</span></div><div class="line"><span class="comment">         mean rate = 96.49 events/second</span></div><div class="line"><span class="comment">     1-minute rate = 96.60 events/second</span></div><div class="line"><span class="comment">     5-minute rate = 96.60 events/second</span></div><div class="line"><span class="comment">    15-minute rate = 96.60 events/second</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">17-11-13 21:58:21 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Meters ----------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestMeters.request</span></div><div class="line"><span class="comment">             count = 855</span></div><div class="line"><span class="comment">         mean rate = 94.85 events/second</span></div><div class="line"><span class="comment">     1-minute rate = 96.60 events/second</span></div><div class="line"><span class="comment">     5-minute rate = 96.60 events/second</span></div><div class="line"><span class="comment">    15-minute rate = 96.60 events/second</span></div><div class="line"><span class="comment">*/</span></div></pre></td></tr></table></figure></p>
<h3 id="Histograms"><a href="#Histograms" class="headerlink" title="Histograms"></a>Histograms</h3><p>Histograms主要使用来统计数据的分布情况，最大值、最小值、平均值、中位数，百分比（75%、90%、95%、98%、99%和99.9%）。例如，需要统计某个页面的请求响应时间分布情况，可以使用该种类型的Metrics进行统计。具体的样例代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestHistograms</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> MetricRegistry metrics = <span class="keyword">new</span> MetricRegistry(<span class="string">"name"</span>);</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).build();</div><div class="line">    <span class="comment">// 实例化一个Histograms</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Histogram randomEum = metrics.histogram(MetricRegistry.name(TestHistograms.class, <span class="string">"random"</span>));</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handleRequest</span><span class="params">(<span class="keyword">double</span> random)</span> </span>&#123;</div><div class="line">        randomEum.update((<span class="keyword">int</span>) (random * <span class="number">100</span>));</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</div><div class="line">        reporter.start(<span class="number">3</span>, TimeUnit.SECONDS);</div><div class="line">        Random random = <span class="keyword">new</span> Random();</div><div class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</div><div class="line">            handleRequest(random.nextDouble());</div><div class="line">            Thread.sleep(<span class="number">100</span>);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">17-11-13 22:00:38 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Histograms ------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestHistograms.random</span></div><div class="line"><span class="comment">             count = 31</span></div><div class="line"><span class="comment">               min = 0</span></div><div class="line"><span class="comment">               max = 98</span></div><div class="line"><span class="comment">              mean = 43.68</span></div><div class="line"><span class="comment">            stddev = 34.26</span></div><div class="line"><span class="comment">            median = 41.00</span></div><div class="line"><span class="comment">              75% &lt;= 77.00</span></div><div class="line"><span class="comment">              95% &lt;= 96.20</span></div><div class="line"><span class="comment">              98% &lt;= 98.00</span></div><div class="line"><span class="comment">              99% &lt;= 98.00</span></div><div class="line"><span class="comment">            99.9% &lt;= 98.00</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">17-11-13 22:00:41 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Histograms ------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestHistograms.random</span></div><div class="line"><span class="comment">             count = 60</span></div><div class="line"><span class="comment">               min = 0</span></div><div class="line"><span class="comment">               max = 98</span></div><div class="line"><span class="comment">              mean = 45.10</span></div><div class="line"><span class="comment">            stddev = 31.09</span></div><div class="line"><span class="comment">            median = 46.00</span></div><div class="line"><span class="comment">              75% &lt;= 72.75</span></div><div class="line"><span class="comment">              95% &lt;= 94.95</span></div><div class="line"><span class="comment">              98% &lt;= 97.78</span></div><div class="line"><span class="comment">              99% &lt;= 98.00</span></div><div class="line"><span class="comment">            99.9% &lt;= 98.00</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">17-11-13 22:00:44 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Histograms ------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestHistograms.random</span></div><div class="line"><span class="comment">             count = 90</span></div><div class="line"><span class="comment">               min = 0</span></div><div class="line"><span class="comment">               max = 98</span></div><div class="line"><span class="comment">              mean = 47.18</span></div><div class="line"><span class="comment">            stddev = 31.06</span></div><div class="line"><span class="comment">            median = 48.50</span></div><div class="line"><span class="comment">              75% &lt;= 77.00</span></div><div class="line"><span class="comment">              95% &lt;= 94.45</span></div><div class="line"><span class="comment">              98% &lt;= 97.18</span></div><div class="line"><span class="comment">              99% &lt;= 98.00</span></div><div class="line"><span class="comment">            99.9% &lt;= 98.00</span></div><div class="line"><span class="comment">*/</span></div></pre></td></tr></table></figure></p>
<h3 id="Timers"><a href="#Timers" class="headerlink" title="Timers"></a>Timers</h3><p>Timers主要是用来统计某一块代码段的执行时间以及其分布情况，具体是基于Histograms和Meters来实现的。样例代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestTimers</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> MetricRegistry metrics = <span class="keyword">new</span> MetricRegistry(<span class="string">"name"</span>);</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).build();</div><div class="line">    <span class="comment">// 实例化一个Timer</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Timer requests = metrics.timer(MetricRegistry.name(TestTimers.class, <span class="string">"request"</span>));</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handleReuqest</span><span class="params">(<span class="keyword">int</span> sleep)</span> </span>&#123;</div><div class="line">        Context context = requests.time();</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            <span class="comment">// 耗时操作</span></div><div class="line">            Thread.sleep(sleep);</div><div class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125; <span class="keyword">finally</span> &#123;</div><div class="line">            context.stop();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">        reporter.start(<span class="number">3</span>, TimeUnit.SECONDS);</div><div class="line">        Random random = <span class="keyword">new</span> Random();</div><div class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</div><div class="line">            handleReuqest(random.nextInt(<span class="number">1000</span>));</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">17-11-13 22:03:29 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Timers ----------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestTimers.request</span></div><div class="line"><span class="comment">             count = 6</span></div><div class="line"><span class="comment">         mean rate = 1.99 calls/second</span></div><div class="line"><span class="comment">     1-minute rate = 0.00 calls/second</span></div><div class="line"><span class="comment">     5-minute rate = 0.00 calls/second</span></div><div class="line"><span class="comment">    15-minute rate = 0.00 calls/second</span></div><div class="line"><span class="comment">               min = 86.93 milliseconds</span></div><div class="line"><span class="comment">               max = 977.19 milliseconds</span></div><div class="line"><span class="comment">              mean = 435.70 milliseconds</span></div><div class="line"><span class="comment">            stddev = 362.66 milliseconds</span></div><div class="line"><span class="comment">            median = 291.05 milliseconds</span></div><div class="line"><span class="comment">              75% &lt;= 836.14 milliseconds</span></div><div class="line"><span class="comment">              95% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment">              98% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment">              99% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment">            99.9% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">17-11-13 22:03:32 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Timers ----------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestTimers.request</span></div><div class="line"><span class="comment">             count = 14</span></div><div class="line"><span class="comment">         mean rate = 2.33 calls/second</span></div><div class="line"><span class="comment">     1-minute rate = 2.20 calls/second</span></div><div class="line"><span class="comment">     5-minute rate = 2.20 calls/second</span></div><div class="line"><span class="comment">    15-minute rate = 2.20 calls/second</span></div><div class="line"><span class="comment">               min = 41.82 milliseconds</span></div><div class="line"><span class="comment">               max = 977.19 milliseconds</span></div><div class="line"><span class="comment">              mean = 390.15 milliseconds</span></div><div class="line"><span class="comment">            stddev = 302.58 milliseconds</span></div><div class="line"><span class="comment">            median = 339.11 milliseconds</span></div><div class="line"><span class="comment">              75% &lt;= 621.34 milliseconds</span></div><div class="line"><span class="comment">              95% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment">              98% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment">              99% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment">            99.9% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">17-11-13 22:03:35 ==============================================================</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">-- Timers ----------------------------------------------------------------------</span></div><div class="line"><span class="comment">Metrics.TestTimers.request</span></div><div class="line"><span class="comment">             count = 20</span></div><div class="line"><span class="comment">         mean rate = 2.22 calls/second</span></div><div class="line"><span class="comment">     1-minute rate = 2.20 calls/second</span></div><div class="line"><span class="comment">     5-minute rate = 2.20 calls/second</span></div><div class="line"><span class="comment">    15-minute rate = 2.20 calls/second</span></div><div class="line"><span class="comment">               min = 41.82 milliseconds</span></div><div class="line"><span class="comment">               max = 977.19 milliseconds</span></div><div class="line"><span class="comment">              mean = 427.92 milliseconds</span></div><div class="line"><span class="comment">            stddev = 294.70 milliseconds</span></div><div class="line"><span class="comment">            median = 355.03 milliseconds</span></div><div class="line"><span class="comment">              75% &lt;= 726.69 milliseconds</span></div><div class="line"><span class="comment">              95% &lt;= 972.35 milliseconds</span></div><div class="line"><span class="comment">              98% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment">              99% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment">            99.9% &lt;= 977.19 milliseconds</span></div><div class="line"><span class="comment">*/</span></div></pre></td></tr></table></figure></p>
<h2 id="Health-Checks"><a href="#Health-Checks" class="headerlink" title="Health Checks"></a>Health Checks</h2><p>Metrics提供了一个独立的模块：Health Checks，用于对Application、其子模块或者关联模块的运行是否正常做检测。该模块是独立metrics-core模块的，使用时则导入metrics-healthchecks包。<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 阿里maven --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.dropwizard.metrics<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>metrics-healthchecks<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.0.0-alpha3<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p>使用起来和与上述几种类型的Metrics有点类似，但是需要重新实例化一个Metrics容器HealthCheckRegistry，待检测模块继承抽象类HealthCheck并实现check()方法即可，然后将该模块注册到HealthCheckRegistry中，判断的时候通过isHealthy()接口即可。如下示例代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DatabaseHealthChecks</span> <span class="keyword">extends</span> <span class="title">HealthCheck</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Database database;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DatabaseHealthChecks</span><span class="params">(Database database)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.database = database;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> Result <span class="title">check</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="keyword">if</span> (database.ping()) &#123;</div><div class="line">            <span class="keyword">return</span> Result.healthy(); <span class="comment">// 健康</span></div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> Result.unhealthy(<span class="string">"Can't ping database."</span>); <span class="comment">// 不良</span></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</div><div class="line">        <span class="comment">// MetricRegistry metrics = new MetricRegistry();</span></div><div class="line">        <span class="comment">// ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).build();</span></div><div class="line">        HealthCheckRegistry registry = <span class="keyword">new</span> HealthCheckRegistry();</div><div class="line">        registry.register(<span class="string">"database1"</span>, <span class="keyword">new</span> DatabaseHealthChecks(<span class="keyword">new</span> Database()));</div><div class="line">        registry.register(<span class="string">"database2"</span>, <span class="keyword">new</span> DatabaseHealthChecks(<span class="keyword">new</span> Database()));</div><div class="line">        <span class="keyword">while</span>(<span class="keyword">true</span>) &#123;</div><div class="line">            <span class="keyword">for</span> (Map.Entry&lt;String, Result&gt; entry : registry.runHealthChecks().entrySet()) &#123;</div><div class="line">                <span class="keyword">if</span>(entry.getValue().isHealthy()) &#123; <span class="comment">// 是否健康</span></div><div class="line">                    System.out.println(entry.getKey() + <span class="string">": OK!"</span>);</div><div class="line">                &#125;<span class="keyword">else</span> &#123;</div><div class="line">                    System.out.println(entry.getKey() + <span class="string">"FAIL, error message: "</span> + entry.getValue().getMessage());</div><div class="line">                    Throwable e = entry.getValue().getError();</div><div class="line">                    <span class="keyword">if</span>(e != <span class="keyword">null</span>) &#123;</div><div class="line">                        e.printStackTrace();</div><div class="line">                    &#125;</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">            Thread.sleep(<span class="number">1000</span>);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Database</span> </span>&#123;</div><div class="line">        <span class="comment">/**</span></div><div class="line"><span class="comment">         * 模拟database的ping方法</span></div><div class="line"><span class="comment">         * <span class="doctag">@return</span> 随机返回boolean值</span></div><div class="line"><span class="comment">         */</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">ping</span><span class="params">()</span> </span>&#123;</div><div class="line">            Random random = <span class="keyword">new</span> Random();</div><div class="line">            <span class="keyword">return</span> random.nextBoolean();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".</span></div><div class="line"><span class="comment">SLF4J: Defaulting to no-operation (NOP) logger implementation</span></div><div class="line"><span class="comment">SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.</span></div><div class="line"><span class="comment">database1: OK!</span></div><div class="line"><span class="comment">database2: OK!</span></div><div class="line"><span class="comment">database1FAIL, error message: Can't ping database.</span></div><div class="line"><span class="comment">database2: OK!</span></div><div class="line"><span class="comment">database1FAIL, error message: Can't ping database.</span></div><div class="line"><span class="comment">database2FAIL, error message: Can't ping database.</span></div><div class="line"><span class="comment">database1FAIL, error message: Can't ping database.</span></div><div class="line"><span class="comment">database2: OK!</span></div><div class="line"><span class="comment">database1: OK!</span></div><div class="line"><span class="comment">database2FAIL, error message: Can't ping database.</span></div><div class="line"><span class="comment">database1FAIL, error message: Can't ping database.</span></div><div class="line"><span class="comment">database2: OK!</span></div><div class="line"><span class="comment">database1FAIL, error message: Can't ping database.</span></div><div class="line"><span class="comment">database2: OK!</span></div><div class="line"><span class="comment">database1: OK!</span></div><div class="line"><span class="comment">database2: OK!</span></div><div class="line"><span class="comment">database1: OK!</span></div><div class="line"><span class="comment">database2FAIL, error message: Can't ping database.</span></div><div class="line"><span class="comment">database1: OK!</span></div><div class="line"><span class="comment">database2: OK!</span></div><div class="line"><span class="comment">database1: OK!</span></div><div class="line"><span class="comment">database2: OK!</span></div><div class="line"><span class="comment">*/</span></div></pre></td></tr></table></figure></p>
<h2 id="其他支持"><a href="#其他支持" class="headerlink" title="其他支持"></a>其他支持</h2><p>metrics提供了对Ehcache、Apache HttpClient、JDBI、Jersey、Jetty、Log4J、Logback、JVM等的集成，可以方便地将Metrics输出到Ganglia、Graphite中，供用户图形化展示。</p>
<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><ul>
<li>学习来源1：<a href="http://www.cnblogs.com/nexiyi/p/metrics_sample_1.html" target="_blank" rel="external">http://www.cnblogs.com/nexiyi/p/metrics_sample_1.html</a></li>
<li>学习来源2：<a href="http://www.cnblogs.com/nexiyi/p/metrics_sample_2.html" target="_blank" rel="external">http://www.cnblogs.com/nexiyi/p/metrics_sample_2.html</a></li>
<li>Github仓库：<a href="https://github.com/dropwizard/metrics" target="_blank" rel="external">https://github.com/dropwizard/metrics</a></li>
<li>官方文档：<a href="http://metrics.dropwizard.io" target="_blank" rel="external">http://metrics.dropwizard.io</a></li>
<li>Hadoop指标框架MetricsV2：<a href="https://wiki.apache.org/hadoop/HADOOP-6728-MetricsV2" target="_blank" rel="external">https://wiki.apache.org/hadoop/HADOOP-6728-MetricsV2</a></li>
</ul>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-12-05T09:58:35.279Z" itemprop="dateUpdated">2017年12月5日 17:58</time>
</span><br>


        如要转载请注明出处：<a href="/2017/11/13/Metrics/" target="_blank" rel="external">http://magic_duck.oschina.io/2017/11/13/Metrics/</a>
    </div>
    <footer>
        <a href="http://magic_duck.oschina.io">
            <img src="/img/avatar.jpg" alt="神奇的鸭鸭">
            神奇的鸭鸭
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/监控平台/">监控平台</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/11/13/Metrics/&title=《Metrics-JVM上的实时监控类库》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/11/13/Metrics/&title=《Metrics-JVM上的实时监控类库》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/11/13/Metrics/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Metrics-JVM上的实时监控类库》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/11/13/Metrics/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/11/13/Metrics/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/11/20/grafana_http_api_1/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">Grafana-HTTPAPI(1)(Authentication篇+DataSource篇)</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/11/09/java_enhance5_使用序列化实现对象的拷贝/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">java提高篇(五) 使用序列化实现对象的拷贝</h4>
      </a>
    </div>
  
</nav>



    







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        我只要一角钱~ ~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.png" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://git.oschina.net/z77z" target="_blank">邹海清</a></span>
            <span>神奇的鸭鸭の码农库 &copy; 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/11/13/Metrics/&title=《Metrics-JVM上的实时监控类库》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/11/13/Metrics/&title=《Metrics-JVM上的实时监控类库》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/11/13/Metrics/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Metrics-JVM上的实时监控类库》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/11/13/Metrics/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/11/13/Metrics/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://magic_duck.oschina.io/2017/11/13/Metrics/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



lazyScripts.push('//s95.cnzz.com/z_stat.php?id=1261081671&web_id=1261081671')

</script>

<script src="/js/main.min.js?v=1.4.3"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.4.3" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
